<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\admin\model\AdminArticle as AdminArticleModel;
use app\admin\model\Shop;
use app\admin\model\DistributeTask;
use app\admin\model\Withdraw;
use app\admin\model\UserOrder;
use think\Db;
use think\Exception;
use think\Session;
use Firebase\JWT\JWT;

/**
 * @internal
 */
class AdminArticle extends Backend
{
    protected $model = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new AdminArticleModel();
        $admin = Session::get('admin');
        $this->admin = $admin;
        $this->assignconfig("admin",$admin);
        $this->assign("admin_id",$admin['id']);
    }


    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit,$page, $alias, $bind,$arr) = $this->buildparams();
            $z_where = [];
            $z_where1 = [];
            if($this->admin['id'] == 1){
                $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            }else{
                $where = [];
                for ($i=0; $i < count($arr); $i++) { 
                    $where[$arr[$i][0]] = [$arr[$i][1],$arr[$i][2]];
                }
                $where1 = $where;
                $where['admin_id'] = $this->admin['id'];
                $where1['audit_admin_id'] = $this->admin['id'];
                $list = $this->model
                ->where($where)
                ->whereOr(function($query) use ($where1){
                    $query->where($where1);
                })
                ->order($sort, $order)
                ->paginate($limit);
            }
            $z_where1['status'] = 2;
            $z_num =AdminArticleModel::where($where)->whereTime('add_time', '-7 days')->count();//周任务总数
            $z_num1 =AdminArticleModel::where($where)->where($z_where1)->whereTime('add_time', '-7 days')->count();//周任务总数
            $z_num2 = 0;

            //周
            $a =AdminArticleModel::where($where)->where(['plan_complete_time'=>['<',time()]])->whereTime('add_time', '-7 days')->count();//周任务总数
            $a1 =AdminArticleModel::where($where)->where(['plan_complete_time'=>['<',time()]])->where($z_where1)->whereTime('add_time', '-7 days')->count();//周任务总数
            if($a>0 && $a1 >0){
                $z_num2 = bcmul(bcdiv($a1, $a, 2),100,2);
            }
            $y_num =AdminArticleModel::where($where)->whereTime('add_time', '-30 days')->count();//月任务总数
            $y_num1 =AdminArticleModel::where($where)->where($z_where1)->whereTime('add_time', '-30 days')->count();//月任务总数
            $y_num2 = 0;

            //月任务完成度
            $a =AdminArticleModel::where($where)->where(['plan_complete_time'=>['<',time()]])->whereTime('add_time', '-30 days')->count();//周任务总数
            $a1 =AdminArticleModel::where($where)->where(['plan_complete_time'=>['<',time()]])->where($z_where1)->whereTime('add_time', '-30 days')->count();//周任务总数
            if($a>0 && $a1 >0){
                $y_num2 = bcmul(bcdiv($a1, $a, 2),100,2);
            }
            $extend = [
                'z_num'=>$z_num,
                'z_num1'=>$z_num1,
                'z_num2'=>$z_num2,
                'y_num'=>$y_num,
                'y_num1'=>$y_num1,
                'y_num2'=>$y_num2,
            ];
            //加减乘除
            //对 $num1 和 $num2 求和。
            //bcadd($num1, $num2, $scale)
            //$num1 减去 $num2。
            //bcsub($num1, $num2, $scale)
            //≈num1 乘以 $num2。
            //bcmul($num1, $num2, $scale)
            //$num1 除以 $num2。
            //bcdiv($num1, $num2, $scale)

            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>$extend);
            return json($result);
        }
        return $this->view->fetch();
    }

    
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function setStatus($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $params = $this->request->request();
        $result = false;
        Db::startTrans();
        try {
            $params['complete_time'] = time();
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if($row['plan_complete_time']){
            $row['plan_complete_time'] = date('Y-m-d H:i:s',$row['plan_complete_time']);
        }
        

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // if($this->admin['id'] != 1 && $this->admin['id'] != $row['audit_admin_id']){
        //     $this->error('请联系管理员进行操作');
        // }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            
            $params['plan_complete_time'] = strtotime($params['plan_complete_time']);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 完成
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function complete($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if($this->admin['id'] != 1){
            if(empty($params['img']) && empty($params['link'])){
                $this->error('附件或链接必须上传一条');
            }
        }
        $result = false;
        Db::startTrans();
        try {
            //上传了指定用户
            if(!empty($params['admin_id']) && $params['admin_id']>0 ){
                $text = [];
                if($row['text']){
                    $text = json_decode($row['text'],true);
                }
                $arr = [
                    'admin_id'=>$row['admin_id'],
                    'link'=>$params['link'],
                    'img'=>$params['img'],
                    'remark'=>$params['remark'],
                    'title'=>$params['title'],
                ];
                $text[] = $arr;
                $arr = ['admin_id'=>$params['admin_id']];
                if(!empty($params['title'])){
                    $arr['title'] = $params['title'];
                } 
                $arr['text'] = json_encode($text,JSON_UNESCAPED_UNICODE);
                $result = $row->allowField(true)->save($arr);
            }else{
                unset($params['admin_id']);
                unset($params['title']);
                unset($params['text']);
                //审核
                $res = $this->audit($params,$row);
                if(!$res){
                    $this->error('任务未完成');
                    Db::rollback();
                }
                //判断是否有审核人
                if(!$row['audit_admin_id']){
                    $params['status'] = 2;
                }   
                $params['complete_time'] = time();
                $result = $row->allowField(true)->save($params);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 任务审核
     *
     * @return string
     * @throws \think\Exception
     */
    public function audit($params,$row)
    {
        //判断日期
        $starttime = strtotime(date('Y-m-d',$row['add_time']));
        $endtime = $starttime + (3600*24);
        
        if($row['pid'] == 15){ //每日余享30个帖子
            $count = DistributeTask::where(['type'=>'余享小红书','status'=>['in','0,1,-2']])->where('add_time', 'between time', [$starttime, $endtime])->count();
            if($count < 30){
                //查询接单时间是否有30个
                $count = DistributeTask::where(['type'=>'余享小红书'])->where('receive_time', 'between time', [$starttime, $endtime])->count();
                if($count < 30){
                    return false;
                }
            }
        }elseif($row['pid'] == 16){//每日电事聚50个帖子
            $count = DistributeTask::where(['type'=>'电事聚小红书','status'=>['in','0,1,-2']])->where('add_time', 'between time', [$starttime, $endtime])->count();
            if($count < 50){
                $count = DistributeTask::where(['type'=>'电事聚小红书'])->where('receive_time', 'between time', [$starttime, $endtime])->count();
                if($count < 50){
                    return false;
                }
            }
        }elseif($row['pid'] == 21){//每日客户提现
            $count = Withdraw::where(['status'=>'created'])->count();
            if($count){
                return false;
            }
        }elseif($row['pid'] == 23){//每日资质狗30个帖子
            $count = DistributeTask::where(['type'=>'资质狗','status'=>['in','0,1,-2']])->where('add_time', 'between time', [$starttime, $endtime])->count();
            
            if($count < 30){
                $count = DistributeTask::where(['type'=>'资质狗'])->where('receive_time', 'between time', [$starttime, $endtime])->count();
             
                if($count < 30){
                    return false;
                }
            }
        }elseif($row['pid'] == 29){//每日审核平台任务
            $count = DistributeTask::where(['status'=>2])->where('add_time', 'between time', [$starttime, $endtime])->count();
            if($count){
                return false;
            }
        }elseif($row['pid'] == 30){//每日处理余享订单发货
            $count = UserOrder::where(['status'=>6])->count();
            if($count){
                return false;
            }
        }
        return true;
    }

    /**
     * 任务审核
     *
     * @return string
     * @throws \think\Exception
     */
    public function setRepetition($ids = null)
    {
        $info = $this->model->where('id',$ids)->update(['repetition'=>0]);
        
        $this->success();
    }
    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function adds()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['add_time'] = time();
        //$params['admin_id'] = $this->admin['id'];
        $params['plan_complete_time'] = strtotime($params['plan_complete_time']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }
    public function addss()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['add_time'] = time();
        //$params['admin_id'] = $this->admin['id'];
        $params['plan_complete_time'] = strtotime($params['plan_complete_time']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['add_time'] = time();
        //$params['admin_id'] = $this->admin['id'];
        $params['plan_complete_time'] = strtotime($params['plan_complete_time']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }
     /**
     * 删除
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function del($ids = null)
    {
        $where = ['id'=>$ids];
        $row =  $this->model->where('id',$ids)->find();
        if($row['status'] == 2){
            $this->error('当前状态无法删除');
        }
        if($this->admin['id'] != 1){
            $this->error('请联系管理员进行操作');
        }
        $row = AdminArticleModel::where($where)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res = AdminArticleModel::where(['id'=>$ids])->delete();
        if (false === $res) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //图片生成
	public function getMiaoHua(){
		$prompt = $this->request->request('prompt');
		$init_image_url = $this->request->request('init_image_url');
        if(!$prompt){
            $prompt = '生成参考图片类似的图出来';
        }
        if(!$init_image_url){
            $init_image_url = null;
        }
        $id = $this->set_models();
		$token = $this->encode_jwt_token();
		$parameters = json_encode(["model_id"=>$id,'prompt'=>$prompt, "init_image_url"=>$init_image_url,'img_url'=>null,'type'=>null]);
        
		$res = getMiaohuaData($token,$parameters);

		if(!empty($res['task_id'])){
            sleep(14);
			$url = 'https://api.sensenova.cn/v1/imgen/internal/generation_tasks/'.$res['task_id'];
			$token = $this->encode_jwt_token();
			$res = getModelsData($token,$url);
			$this->success($res);
		}

		dd($res);
    }
    
	//模型信息查询
	public function set_models(){
        $token = $this->encode_jwt_token();
  
        $res = getModelsData($token);
   
		$id = $res['data'][1]['id'];

		return $id;
    }
    
	//权限鉴权
    public function encode_jwt_token($ak = '71BD02CA207C4A74867C0D0F9C175F1B',$sk='C047D0BA4FAE46BC8AE6C060CAE2A677'){
        $headers = [
            'alg'=>'HS256',
            'typ'=>'JWT'
        ];
        
        $payload =[
            'iss'=> $ak,
            'exp' => time()+ 1800,
            'nbf'=> time()-5
        ];
        // 1! 填写您期望的有效时间，此处示例代表当前时间+30分钟'nbf'=> time()-5，1! 填写您期望的生效时间，此处示例代表当前时间-5秒
        $token=JWT::encode($payload,$sk,'HS256',null,$headers);
        return $token;
        // $authorization=encode iwt token($ak，$sk);
    }
    

    public function getMoonshotAi(){
		set_time_limit(0);
		$title = $this->request->request('title','');
		$content = $this->request->request('content','');
		$user_id = $this->request->request('user_id','');
		$shop_id = $this->request->request('shop_id','');
		$ai_num = $this->request->request('ai_num',1);
		$text = $this->request->request('img_title','');
		$img = $this->request->request('img','');

		//$content = str_replace(PHP_EOL, '', $content);
		//$title = str_replace(PHP_EOL, '', $title);

		//$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
		$query = $content;// '用提供的标题和内容生成一篇小红书笔记，包含标题，内容和话题，内容长度不超过原文的120%。标题：'.$title.'。内容：'.$content.'。';
		if(!$query){
			$this->error('参数错误');
		}

		$arr = [];
		for ($i=0; $i < $ai_num; $i++) { 
			// if($text){
			// 	$data = $this->disposeImg_1($img,3,$text,1);
			// }else{
			// 	$data = $this->disposeImg_1($img,2,$text,1);
			// }
            $data['new_url'] = '';
			$shop = Shop::where(['id'=>$shop_id])->find();
			if(!$shop){
				$this->error('商户信息错误');
			}
			/* if($shop['ai_num'] <= 0 && $shop['balance'] < 0.05){
				break;
			} */
			$res = getMoonshotData($query,$user_id,$shop_id);

			if($res['code'] == 1){
				$res['data']['img'] = $data['new_url'];
				$res['data']['class'] = 'dan';
				$res['data']['ai_img_title'] = $text;
				$arr[] = $res['data'];
			}elseif($res['code'] == -2){
				//重新请求一次
				$query = '注意：请区分“标题”和“内容”两部分!'.$query;
				$res = getMoonshotData($query,$user_id,$shop_id);
				if($res['code'] == 1){
					$res['data']['img'] = $data['new_url'];
					$res['data']['ai_img_title'] = $text;
					$res['data']['class'] = 'dan';
					$arr[] = $res['data'];
				}
			}


			
		}
		if($arr){
			return $arr;
		}else{
			$this->error('AI生成错误,请重新操作');
		}

	}


}